package com.roadjava.rbac.service.impl;

import com.alibaba.fastjson.JSON;
import com.roadjava.rbac.bean.entity.ResourceDoc;
import com.roadjava.rbac.es.PageResult;
import com.roadjava.rbac.es.RequestParams;
import com.roadjava.rbac.mapper.EsMapper;
import com.roadjava.rbac.service.EsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("resource");
            // 2.准备请求参数
            // 2.1.query
           String key = params.getKey();
           if (key == null || "".equals(key)) {
               request.source().query(QueryBuilders.matchAllQuery());
           }else{
               request.source().query(QueryBuilders.matchQuery("all_fields", key));
           }
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }


    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ResourceDoc> resources = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ResourceDoc resourceDoc = JSON.parseObject(json, ResourceDoc.class);
            resources.add(resourceDoc);
        }
       // 4.4.返回结果
        return new PageResult(total,resources);
    }
}
